import adapter.AdvancedWeeder;
import adapter.AdvancedWeederAdapter;
import agricultural.AgriculturalMachine;
import cloud.CloudManagementPlatform;
import factory.MachineType;
import observer.EnvironmentDataCollector;
import pathplanning.PathPlanning;
import safety.SafetyEventType;
import safety.SafetyHandler;
import safety.impl.FaultDetectionHandler;
import safety.impl.ObstacleAvoidanceHandler;
import safety.impl.PathAdjustmentHandler;
import systemmanagement.LogManagement;
import systemmanagement.SystemHealthMonitor;
import systemmanagement.UserManagement;

import java.util.Scanner;

public class Main2 {
    public static void main(String[] args) {
        // 初始化系统
        EnvironmentDataCollector environmentDataCollector = new EnvironmentDataCollector();
        CloudManagementPlatform cloudPlatform = CloudManagementPlatform.getInstance();
        PathPlanning pathPlanning = new PathPlanning();
        UserManagement userManagement = new UserManagement();
        LogManagement logManagement = new LogManagement();
        SystemHealthMonitor systemHealthMonitor = new SystemHealthMonitor();

        // 创建农机设备
        AgriculturalMachine tractor = cloudPlatform.createAgriculturalMachine(MachineType.TRACTOR, "拖拉机-001");
//        AgriculturalMachineFactory factory = new TractorFactory();
//        AgriculturalMachine tractor = factory.createMachine("拖拉机-001");
        AgriculturalMachine planter = cloudPlatform.createAgriculturalMachine(MachineType.PLANTER, "播种机-001");
        AgriculturalMachine harvester = cloudPlatform.createAgriculturalMachine(MachineType.HARVESTER, "收割机-001");
        AgriculturalMachine sprayer = cloudPlatform.createAgriculturalMachine(MachineType.SPRAYER, "喷药机-001");
        // 集成新设备
        AdvancedWeeder advancedWeeder = new AdvancedWeeder("智能除草机-001");
        AgriculturalMachine adaptedWeeder = new AdvancedWeederAdapter(advancedWeeder);

        // 注册观察者
        environmentDataCollector.registerObserver(tractor);
        environmentDataCollector.registerObserver(planter);
        environmentDataCollector.registerObserver(harvester);
        environmentDataCollector.registerObserver(sprayer);
        environmentDataCollector.registerObserver(adaptedWeeder);

        // 设置安全责任链
        SafetyHandler obstacleAvoidanceHandler = new ObstacleAvoidanceHandler();
        SafetyHandler pathAdjustmentHandler = new PathAdjustmentHandler();
        SafetyHandler faultDetectionHandler = new FaultDetectionHandler();

        obstacleAvoidanceHandler.setNextHandler(pathAdjustmentHandler);
        pathAdjustmentHandler.setNextHandler(faultDetectionHandler);

        // 用户权限管理
        userManagement.addUser("admin", "管理员权限");
        userManagement.addUser("user", "普通用户权限");

        Scanner scanner = new Scanner(System.in);
        boolean running = true;

        while (running) {
            System.out.println("\n欢迎使用智能农业系统，请选择操作:");
            System.out.println("1. 农田环境监测");
            System.out.println("2. 模拟安全事件");
            System.out.println("3. 模拟任务分配");
            System.out.println("4. 模拟路径规划");
            System.out.println("5. 模拟远程控制");
            System.out.println("6. 系统管理操作");
            System.out.println("7. 退出");

            int choice = getValidIntInput(scanner, "请输入有效的操作编号: ");

            switch (choice) {
                case 1:
                    System.out.println("1. 采集土壤数据和气象数据");
                    System.out.println("2. 显示作物生长环境状态");
                    if(scanner.nextInt()==1) {
                        inputEnvironmentData(scanner, environmentDataCollector);
                    }else{
                        System.out.println("土壤湿度: " + environmentDataCollector.getSoilMoisture() + "%"+"pH值: " + environmentDataCollector.getSoilPH()+"养分含量: " + environmentDataCollector.getSoilNutrient() + "%");
                        System.out.println("天气数据: " );
                        System.out.println("温度: " + environmentDataCollector.getTemperature() + "°C");
                        System.out.println("湿度: " + environmentDataCollector.getHumidity() + "%");
                        System.out.println("风速: " + environmentDataCollector.getWindSpeed() + "m/s");

                    }
                    break;
                case 2:
                    simulateSafetyEvent(scanner, obstacleAvoidanceHandler, tractor, planter, harvester, sprayer, adaptedWeeder);
                    break;
                case 3:
                    simulateTaskAssignment(scanner, cloudPlatform);
                    break;
                case 4:
                    simulatePathPlanning(scanner, pathPlanning, tractor, planter, harvester, sprayer, adaptedWeeder);
                    break;
                case 5:
                    simulateRemoteControl(scanner, tractor, planter, harvester, sprayer, adaptedWeeder);
                    break;
                case 6:
                    systemManagementOperations(scanner, userManagement, logManagement, systemHealthMonitor);
                    break;
                case 7:
                    running = false;
                    System.out.println("感谢使用智能农业系统，再见！");
                    break;
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
        scanner.close();
    }

    private static int getValidIntInput(Scanner scanner, String prompt) {
        while (true) {
            try {
                return scanner.nextInt();
            } catch (Exception e) {
                scanner.nextLine(); // 消耗无效输入
                System.out.print(prompt);
            }
        }
    }

    private static void inputEnvironmentData(Scanner scanner, EnvironmentDataCollector environmentDataCollector) {
        System.out.println("请输入土壤湿度 (%):");
        double soilMoisture = scanner.nextDouble();
        if(soilMoisture<0 || soilMoisture>100){
            System.out.println("土壤湿度范围为0-100，请重新输入。");
            return;
        }else if(soilMoisture<20){
            System.out.println("土壤湿度过低，请及时补充水分。");
        }
        scanner.nextLine(); // 消耗换行符
        System.out.println("请输入土壤pH值:");
        double soilPH = scanner.nextDouble();
        if(soilPH<0 || soilPH>14){
            System.out.println("土壤pH值范围为0-14，请重新输入。");
            return;
        }else if(soilPH<5){
            System.out.println("土壤pH值过低，请及时进行pH值调节。");
        }else if(soilPH>7){
            System.out.println("土壤pH值过高，请及时进行pH值调节。");
        }
        scanner.nextLine(); // 消耗换行符
        System.out.println("请输入土壤养分含量 (%):");
        double soilNutrient = scanner.nextDouble();
        if(soilNutrient<0 || soilNutrient>100){
            System.out.println("土壤养分含量范围为0-100，请重新输入。");
            return;
        }else if(soilNutrient<20){
            System.out.println("土壤养分含量过低，请及时进行养分补充。");
        }else if(soilNutrient>80){
            System.out.println("土壤养分含量过高，请及时进行养分调节。");
        }
        scanner.nextLine(); // 消耗换行符
        System.out.println("请输入温度 (°C):");
        double temperature = scanner.nextDouble();
        if(temperature<-10 || temperature>40){
            System.out.println("温度范围为-10-40°C，请重新输入。");
            return;
        }else if(temperature<-10){
            System.out.println("温度过低，请及时进行降温。");
        }else if(temperature>40){
            System.out.println("温度过高，请及时进行降温。");
        }
        scanner.nextLine(); // 消耗换行符
        System.out.println("请输入湿度 (%):");
        double humidity = scanner.nextDouble();
        if(humidity<0 || humidity>100){
            System.out.println("湿度范围为0-100，请重新输入。");
            return;
        }else if(humidity<20){
            System.out.println("湿度过低，请及时进行加湿。");
        }else if(humidity>80){
            System.out.println("湿度过高，请及时进行加湿。");
        }
        scanner.nextLine(); // 消耗换行符
        System.out.println("请输入风速 (m/s):");
        double windSpeed = scanner.nextDouble();
        if(windSpeed<0 || windSpeed>50){
            System.out.println("风速范围为0-50m/s，请重新输入。");
            return;
        }else if(windSpeed>10){
            System.out.println("风速过高，请及时进行通风。");
        }
        scanner.nextLine(); // 消耗换行符
        environmentDataCollector.setSoilMoisture(soilMoisture);
        environmentDataCollector.setSoilPH(soilPH);
        environmentDataCollector.setSoilNutrient(soilNutrient);
        environmentDataCollector.setTemperature(temperature);
        environmentDataCollector.setHumidity(humidity);
        environmentDataCollector.setWindSpeed(windSpeed);
    }

    private static void simulateSafetyEvent(Scanner scanner, SafetyHandler obstacleAvoidanceHandler,
                                            AgriculturalMachine tractor, AgriculturalMachine planter,
                                            AgriculturalMachine harvester, AgriculturalMachine sprayer,
                                            AgriculturalMachine adaptedWeeder) {
        scanner.nextLine(); // 消耗换行符
        System.out.println("请选择安全事件类型 (OBSTACLE_DETECTED, FENCE_BREACH, FAULT_DETECTED):");
        String eventTypeStr = scanner.nextLine();
        try {
            SafetyEventType eventType = SafetyEventType.valueOf(eventTypeStr);
            System.out.println("请选择农机设备 (1.拖拉机-001, 2.播种机-001, 3.收割机-001, 4.喷药机-001, 5.智能除草机-001):");
            String machineId = scanner.nextLine();
            AgriculturalMachine selectedMachine = getSelectedMachine(machineId, tractor, planter, harvester, sprayer, adaptedWeeder);
            if (selectedMachine != null) {
                obstacleAvoidanceHandler.handleSafetyEvent(eventType, selectedMachine);
            } else {
                System.out.println("无效的农机设备选择");
            }
        } catch (IllegalArgumentException e) {
            System.out.println("无效的安全事件类型，请重新输入。");
        }
    }

    private static void simulateTaskAssignment(Scanner scanner, CloudManagementPlatform cloudPlatform) {
        scanner.nextLine(); // 消耗换行符
        System.out.println("请输入作业区域:");
        String area = scanner.nextLine();
        System.out.println("请输入任务类型 (播种, 收割, 耕地, 喷药):");
        String taskType = scanner.nextLine();
        System.out.println("请输入工作量 (公顷):");
        double workload = scanner.nextDouble();
        scanner.nextLine(); // 消耗换行符
        cloudPlatform.assignTask(area, taskType, workload);
    }

    private static void simulatePathPlanning(Scanner scanner, PathPlanning pathPlanning,
                                             AgriculturalMachine tractor, AgriculturalMachine planter,
                                             AgriculturalMachine harvester, AgriculturalMachine sprayer,
                                             AgriculturalMachine adaptedWeeder) {
        scanner.nextLine(); // 消耗换行符
        System.out.println("请选择农机设备 (1.拖拉机-001, 2.播种机-001, 3.收割机-001, 4.喷药机-001, 5.智能除草机-001):");
        String machineId = scanner.nextLine();
        AgriculturalMachine selectedMachine = getSelectedMachine(machineId, tractor, planter, harvester, sprayer, adaptedWeeder);
        if (selectedMachine != null) {
            System.out.println("请输入农田状况:");
            String fieldCondition = scanner.nextLine();
            String path = pathPlanning.calculatePath(selectedMachine, fieldCondition);
            System.out.println(selectedMachine.getMachineId() + " 计算得到的路径为: " + path);
        } else {
            System.out.println("无效的农机设备选择");
        }
    }

    private static void simulateRemoteControl(Scanner scanner, AgriculturalMachine tractor,
                                              AgriculturalMachine planter, AgriculturalMachine harvester,
                                              AgriculturalMachine sprayer, AgriculturalMachine adaptedWeeder) {
        scanner.nextLine(); // 消耗换行符
        System.out.println("请选择农机设备 (1.拖拉机-001, 2.播种机-001, 3.收割机-001, 4.喷药机-001, 5.智能除草机-001):");
        String machineId = scanner.nextLine();
        AgriculturalMachine selectedMachine = getSelectedMachine(machineId, tractor, planter, harvester, sprayer, adaptedWeeder);
        if (selectedMachine != null) {

            System.out.println("请输入远程控制指令:");
            String command = scanner.nextLine();
            selectedMachine.receiveRemoteCommand(command);
        } else {
            System.out.println("无效的农机设备选择");
        }
    }

    private static void systemManagementOperations(Scanner scanner, UserManagement userManagement,
                                                   LogManagement logManagement, SystemHealthMonitor systemHealthMonitor) {
        scanner.nextLine(); // 消耗换行符
        System.out.println("请选择系统管理操作 (1.用户权限管理, 2.作业日志记录与分析, 3.系统健康监测):");
        String systemOperation = scanner.nextLine();
        if ("1".equals(systemOperation)) {
            System.out.println("请输入用户名:");
            String username = scanner.nextLine();
            System.out.println("请输入权限:");
            String permission = scanner.nextLine();
            userManagement.addUser(username, permission);
        } else if ("2".equals(systemOperation)) {
            System.out.println("请输入日志内容:");
            String log = scanner.nextLine();
            logManagement.recordLog(log);
            logManagement.analyzeLogs();
        } else if ("3".equals(systemOperation)) {
            systemHealthMonitor.monitorSystemHealth();
        } else {
            System.out.println("无效的系统管理操作选择，请重新输入。");
        }
    }

    private static AgriculturalMachine getSelectedMachine(String machineId, AgriculturalMachine tractor,
                                                          AgriculturalMachine planter, AgriculturalMachine harvester,
                                                          AgriculturalMachine sprayer, AgriculturalMachine adaptedWeeder) {
        switch (machineId) {
            case "1":
                return tractor;
            case "2":
                return planter;
            case "3":
                return harvester;
            case "4":
                return sprayer;
            case "5":
                return adaptedWeeder;
            default:
                return null;
        }
    }
}